home *** CD-ROM | disk | FTP | other *** search
/ EuroCD 3 / EuroCD 3.iso / Programming / Python-1.4 / Lib / rexec.py < prev    next >
Text File  |  1998-06-24  |  10KB  |  385 lines

  1. """Restricted execution facilities.
  2.  
  3. The class RExec exports methods r_exec(), r_eval(), r_execfile(), and
  4. r_import(), which correspond roughly to the built-in operations
  5. exec, eval(), execfile() and import, but executing the code in an
  6. environment that only exposes those built-in operations that are
  7. deemed safe.  To this end, a modest collection of 'fake' modules is
  8. created which mimics the standard modules by the same names.  It is a
  9. policy decision which built-in modules and operations are made
  10. available; this module provides a reasonable default, but derived
  11. classes can change the policies e.g. by overriding or extending class
  12. variables like ok_builtin_modules or methods like make_sys().
  13.  
  14. XXX To do:
  15. - r_open should allow writing tmp dir
  16. - r_exec etc. with explicit globals/locals? (Use rexec("exec ... in ...")?)
  17.  
  18. """
  19.  
  20.  
  21. import sys
  22. import __builtin__
  23. import os
  24. import marshal
  25. import ihooks
  26.  
  27.  
  28. class FileBase:
  29.  
  30.     ok_file_methods = ('fileno', 'flush', 'isatty', 'read', 'readline',
  31.         'readlines', 'seek', 'tell', 'write', 'writelines')
  32.  
  33.  
  34. class FileWrapper(FileBase):
  35.  
  36.     # XXX This is just like a Bastion -- should use that!
  37.  
  38.     def __init__(self, f):
  39.         self.f = f
  40.         for m in self.ok_file_methods:
  41.             if not hasattr(self, m) and hasattr(f, m):
  42.                 setattr(self, m, getattr(f, m))
  43.     
  44.     def close(self):
  45.         self.flush()
  46.  
  47.  
  48. TEMPLATE = """
  49. def %s(self, *args):
  50.     return apply(getattr(self.mod, self.name).%s, args)
  51. """
  52.  
  53. class FileDelegate(FileBase):
  54.  
  55.     def __init__(self, mod, name):
  56.         self.mod = mod
  57.         self.name = name
  58.     
  59.     for m in FileBase.ok_file_methods + ('close',):
  60.         exec TEMPLATE % (m, m)
  61.  
  62.  
  63. class RHooks(ihooks.Hooks):
  64.  
  65.     def __init__(self, *args):
  66.     # Hacks to support both old and new interfaces:
  67.     # old interface was RHooks(rexec[, verbose])
  68.     # new interface is RHooks([verbose])
  69.     verbose = 0
  70.     rexec = None
  71.     if args and type(args[-1]) == type(0):
  72.         verbose = args[-1]
  73.         args = args[:-1]
  74.     if args and hasattr(args[0], '__class__'):
  75.         rexec = args[0]
  76.         args = args[1:]
  77.     if args:
  78.         raise TypeError, "too many arguments"
  79.     ihooks.Hooks.__init__(self, verbose)
  80.     self.rexec = rexec
  81.  
  82.     def set_rexec(self, rexec):
  83.     # Called by RExec instance to complete initialization
  84.     self.rexec = rexec
  85.  
  86.     def is_builtin(self, name):
  87.     return self.rexec.is_builtin(name)
  88.  
  89.     def init_builtin(self, name):
  90.     m = __import__(name)
  91.     return self.rexec.copy_except(m, ())
  92.  
  93.     def init_frozen(self, name): raise SystemError, "don't use this"
  94.     def load_source(self, *args): raise SystemError, "don't use this"
  95.     def load_compiled(self, *args): raise SystemError, "don't use this"
  96.  
  97.     def load_dynamic(self, name, filename, file):
  98.     return self.rexec.load_dynamic(name, filename, file)
  99.  
  100.     def add_module(self, name):
  101.     return self.rexec.add_module(name)
  102.  
  103.     def modules_dict(self):
  104.     return self.rexec.modules
  105.  
  106.     def default_path(self):
  107.     return self.rexec.modules['sys'].path
  108.  
  109.  
  110. class RModuleLoader(ihooks.FancyModuleLoader):
  111.  
  112.     def load_module(self, name, stuff):
  113.         file, filename, info = stuff
  114.         m = ihooks.FancyModuleLoader.load_module(self, name, stuff)
  115.         m.__filename__ = filename
  116.         return m
  117.  
  118.  
  119. class RModuleImporter(ihooks.ModuleImporter):
  120.  
  121.     def reload(self, module, path=None):
  122.         if path is None and hasattr(module, '__filename__'):
  123.         head, tail = os.path.split(module.__filename__)
  124.         path = [os.path.join(head, '')]
  125.         return ihooks.ModuleImporter.reload(self, module, path)
  126.  
  127.  
  128. class RExec(ihooks._Verbose):
  129.  
  130.     """Restricted Execution environment."""
  131.  
  132.     ok_path = tuple(sys.path)        # That's a policy decision
  133.  
  134.     ok_builtin_modules = ('audioop', 'array', 'binascii',
  135.               'cmath', 'errno', 'imageop',
  136.               'marshal', 'math', 'md5', 'operator',
  137.               'parser', 'regex', 'rotor', 'select',
  138.               'strop', 'struct', 'time')
  139.  
  140.     ok_posix_names = ('error', 'fstat', 'listdir', 'lstat', 'readlink',
  141.               'stat', 'times', 'uname', 'getpid', 'getppid',
  142.               'getcwd', 'getuid', 'getgid', 'geteuid', 'getegid')
  143.  
  144.     ok_sys_names = ('ps1', 'ps2', 'copyright', 'version',
  145.             'platform', 'exit', 'maxint')
  146.  
  147.     nok_builtin_names = ('open', 'reload', '__import__')
  148.  
  149.     def __init__(self, hooks = None, verbose = 0):
  150.     ihooks._Verbose.__init__(self, verbose)
  151.     # XXX There's a circular reference here:
  152.     self.hooks = hooks or RHooks(verbose)
  153.     self.hooks.set_rexec(self)
  154.     self.modules = {}
  155.     self.ok_dynamic_modules = self.ok_builtin_modules
  156.     list = []
  157.     for mname in self.ok_builtin_modules:
  158.         if mname in sys.builtin_module_names:
  159.         list.append(mname)
  160.     self.ok_builtin_modules = list
  161.     self.set_trusted_path()
  162.     self.make_builtin()
  163.     self.make_initial_modules()
  164.     # make_sys must be last because it adds the already created
  165.     # modules to its builtin_module_names
  166.     self.make_sys()
  167.     self.loader = RModuleLoader(self.hooks, verbose)
  168.     self.importer = RModuleImporter(self.loader, verbose)
  169.  
  170.     def set_trusted_path(self):
  171.     # Set the path from which dynamic modules may be loaded.
  172.     # Those dynamic modules must also occur in ok_builtin_modules
  173.     self.trusted_path = filter(os.path.isabs, sys.path)
  174.  
  175.     def load_dynamic(self, name, filename, file):
  176.     if name not in self.ok_dynamic_modules:
  177.         raise ImportError, "untrusted dynamic module: %s" % name
  178.     if sys.modules.has_key(name):
  179.         src = sys.modules[name]
  180.     else:
  181.         import imp
  182.         src = imp.load_dynamic(name, filename, file)
  183.     dst = self.copy_except(src, [])
  184.     return dst
  185.  
  186.     def make_initial_modules(self):
  187.     self.make_main()
  188.     self.make_osname()
  189.  
  190.     # Helpers for RHooks
  191.  
  192.     def is_builtin(self, mname):
  193.     return mname in self.ok_builtin_modules
  194.  
  195.     # The make_* methods create specific built-in modules
  196.  
  197.     def make_builtin(self):
  198.     m = self.copy_except(__builtin__, self.nok_builtin_names)
  199.     m.__import__ = self.r_import
  200.     m.reload = self.r_reload
  201.     m.open = self.r_open
  202.  
  203.     def make_main(self):
  204.     m = self.add_module('__main__')
  205.  
  206.     def make_osname(self):
  207.     osname = os.name
  208.     src = __import__(osname)
  209.     dst = self.copy_only(src, self.ok_posix_names)
  210.     dst.environ = e = {}
  211.     for key, value in os.environ.items():
  212.         e[key] = value
  213.  
  214.     def make_sys(self):
  215.     m = self.copy_only(sys, self.ok_sys_names)
  216.     m.modules = self.modules
  217.     m.argv = ['RESTRICTED']
  218.     m.path = map(None, self.ok_path)
  219.     m = self.modules['sys']
  220.     m.builtin_module_names = \
  221.         self.modules.keys() + self.ok_builtin_modules
  222.     m.builtin_module_names.sort()
  223.  
  224.     # The copy_* methods copy existing modules with some changes
  225.  
  226.     def copy_except(self, src, exceptions):
  227.     dst = self.copy_none(src)
  228.     for name in dir(src):
  229.         setattr(dst, name, getattr(src, name))
  230.     for name in exceptions:
  231.         try:
  232.         delattr(dst, name)
  233.         except AttributeError:
  234.         pass
  235.     return dst
  236.  
  237.     def copy_only(self, src, names):
  238.     dst = self.copy_none(src)
  239.     for name in names:
  240.         try:
  241.         value = getattr(src, name)
  242.         except AttributeError:
  243.         continue
  244.         setattr(dst, name, value)
  245.     return dst
  246.  
  247.     def copy_none(self, src):
  248.     return self.add_module(src.__name__)
  249.  
  250.     # Add a module -- return an existing module or create one
  251.  
  252.     def add_module(self, mname):
  253.     if self.modules.has_key(mname):
  254.         return self.modules[mname]
  255.     self.modules[mname] = m = self.hooks.new_module(mname)
  256.     m.__builtins__ = self.modules['__builtin__']
  257.     return m
  258.  
  259.     # The r* methods are public interfaces
  260.  
  261.     def r_exec(self, code):
  262.     m = self.add_module('__main__')
  263.     exec code in m.__dict__
  264.  
  265.     def r_eval(self, code):
  266.     m = self.add_module('__main__')
  267.     return eval(code, m.__dict__)
  268.  
  269.     def r_execfile(self, file):
  270.     m = self.add_module('__main__')
  271.     return execfile(file, m.__dict__)
  272.  
  273.     def r_import(self, mname, globals={}, locals={}, fromlist=[]):
  274.     return self.importer.import_module(mname, globals, locals, fromlist)
  275.  
  276.     def r_reload(self, m):
  277.         return self.importer.reload(m)
  278.  
  279.     def r_unload(self, m):
  280.         return self.importer.unload(m)
  281.     
  282.     # The s_* methods are similar but also swap std{in,out,err}
  283.  
  284.     def make_delegate_files(self):
  285.         s = self.modules['sys']
  286.     self.delegate_stdin = FileDelegate(s, 'stdin')
  287.     self.delegate_stdout = FileDelegate(s, 'stdout')
  288.     self.delegate_stderr = FileDelegate(s, 'stderr')
  289.         self.restricted_stdin = FileWrapper(sys.stdin)
  290.         self.restricted_stdout = FileWrapper(sys.stdout)
  291.         self.restricted_stderr = FileWrapper(sys.stderr)
  292.  
  293.     def set_files(self):
  294.     if not hasattr(self, 'save_stdin'):
  295.         self.save_files()
  296.     if not hasattr(self, 'delegate_stdin'):
  297.         self.make_delegate_files()
  298.         s = self.modules['sys']
  299.     s.stdin = self.restricted_stdin
  300.     s.stdout = self.restricted_stdout
  301.     s.stderr = self.restricted_stderr
  302.     sys.stdin = self.delegate_stdin
  303.     sys.stdout = self.delegate_stdout
  304.     sys.stderr = self.delegate_stderr
  305.  
  306.     def reset_files(self):
  307.     self.restore_files()
  308.         s = self.modules['sys']
  309.     self.restricted_stdin = s.stdin
  310.     self.restricted_stdout = s.stdout
  311.     self.restricted_stderr = s.stderr
  312.     
  313.  
  314.     def save_files(self):
  315.         self.save_stdin = sys.stdin
  316.         self.save_stdout = sys.stdout
  317.         self.save_stderr = sys.stderr
  318.  
  319.     def restore_files(self):
  320.     sys.stdin = self.save_stdin
  321.     sys.stdout = self.save_stdout
  322.     sys.stderr = self.save_stderr
  323.     
  324.     def s_apply(self, func, args=(), kw=None):
  325.     self.save_files()
  326.     try:
  327.         self.set_files()
  328.         if kw:
  329.         r = apply(func, args, kw)
  330.         else:
  331.         r = apply(func, args)
  332.         finally:
  333.         self.restore_files()
  334.     
  335.     def s_exec(self, *args):
  336.         self.s_apply(self.r_exec, args)
  337.     
  338.     def s_eval(self, *args):
  339.         self.s_apply(self.r_eval, args)
  340.     
  341.     def s_execfile(self, *args):
  342.         self.s_apply(self.r_execfile, args)
  343.     
  344.     def s_import(self, *args):
  345.         self.s_apply(self.r_import, args)
  346.     
  347.     def s_reload(self, *args):
  348.         self.s_apply(self.r_reload, args)
  349.     
  350.     def s_unload(self, *args):
  351.         self.s_apply(self.r_unload, args)
  352.     
  353.     # Restricted open(...)
  354.     
  355.     def r_open(self, file, mode='r', buf=-1):
  356.         if mode not in ('r', 'rb'):
  357.             raise IOError, "can't open files for writing in restricted mode"
  358.         return open(file, mode, buf)
  359.  
  360.  
  361. def test():
  362.     import traceback
  363.     r = RExec(verbose=('-v' in sys.argv[1:]))
  364.     print "*** RESTRICTED *** Python", sys.version
  365.     print sys.copyright
  366.     while 1:
  367.     try:
  368.         try:
  369.         s = raw_input('>>> ')
  370.         except EOFError:
  371.         print
  372.         break
  373.         if s and s[0] != '#':
  374.         s = s + '\n'
  375.         c = compile(s, '<stdin>', 'single')
  376.         r.r_exec(c)
  377.     except SystemExit, n:
  378.         sys.exit(n)
  379.     except:
  380.         traceback.print_exc()
  381.  
  382.  
  383. if __name__ == '__main__':
  384.     test()
  385.